package com.lzc.tlmail.tlmailproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzc.tlmail.tlmailproduct.dao.AttrAttrgroupRelationDao;
import com.lzc.tlmail.tlmailproduct.dao.AttrGroupDao;
import com.lzc.tlmail.tlmailproduct.dao.CategoryDao;
import com.lzc.tlmail.tlmailproduct.entity.AttrAttrgroupRelationEntity;
import com.lzc.tlmail.tlmailproduct.entity.AttrGroupEntity;
import com.lzc.tlmail.tlmailproduct.entity.CategoryEntity;
import com.lzc.tlmail.tlmailproduct.service.AttrAttrgroupRelationService;
import com.lzc.tlmail.tlmailproduct.service.AttrGroupService;
import com.lzc.tlmail.tlmailproduct.service.CategoryService;
import com.lzc.tlmail.tlmailproduct.vo.AttrrespVo;
import com.lzc.tlmail.tlmailproduct.vo.Attrvo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzc.common.utils.PageUtils;
import com.lzc.common.utils.Query;

import com.lzc.tlmail.tlmailproduct.dao.AttrDao;
import com.lzc.tlmail.tlmailproduct.entity.AttrEntity;
import com.lzc.tlmail.tlmailproduct.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {


    @Resource
    private CategoryService categoryService;
    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Resource
    private CategoryDao categoryDao;
    @Resource
    private AttrGroupDao attrGroupDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(Attrvo attr) {
        //先添加基本属性
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.getBaseMapper().insert(attrEntity);
        if (attr.getAttrType() == 1 && attr.getAttrGroupId() != null) {
            //再添加关联关系
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }

    }

    /**
     * 根据分类分页查询规格参数
     *
     * @param params
     * @param catelogId
     */
    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_type", "base".equalsIgnoreCase(type) ? 1 : 0);
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> list = (List<AttrEntity>) pageUtils.getList();
        List<AttrrespVo> attrrespVoList = list.stream().map(attrEntity -> {
            AttrrespVo attrrespVo = new AttrrespVo();
            BeanUtils.copyProperties(attrEntity, attrrespVo);

            if (type.equalsIgnoreCase("base")) {
                //得到分组名称
                AttrAttrgroupRelationEntity attrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attrgroupRelationEntity != null && attrgroupRelationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelationEntity.getAttrGroupId());
                    attrrespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrrespVo.setCatelogName(categoryEntity.getName());
            }
            return attrrespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrrespVoList);
        return pageUtils;

    }

    /**
     * 根据属性id得到属性信息
     *
     * @param attrId
     * @return
     */
    @Override
    public AttrrespVo getAttrInfo(Long attrId) {
        AttrrespVo attrrespVo = new AttrrespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrrespVo);

        AttrAttrgroupRelationEntity attrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (attrgroupRelationEntity != null) {
            attrrespVo.setAttrGroupId(attrgroupRelationEntity.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelationEntity.getAttrGroupId());
            if (attrGroupEntity != null) {
                attrrespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }

        }
        if (attrEntity.getCatelogId() != null) {
            Long[] pathsById = categoryService.getPathsById(attrEntity.getCatelogId());
            attrrespVo.setCatelogPath(pathsById);
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrrespVo.setCatelogName(categoryEntity.getName());
            }

        }

        return attrrespVo;
    }

    /**
     * 修改属性
     *
     * @param attr
     */
    @Transactional
    @Override
    public void updateAttr(Attrvo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.getBaseMapper().updateById(attrEntity);

        if (attr.getAttrType() == 1) {
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            //再修改关联关系
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            if (count > 0) {
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }


    }

    /**
     * 根据分组id的所有属性
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> attrServicegetAttrById(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId));
        List<Long> attrids = attrAttrgroupRelationEntities.stream().map(attrAttrgroupRelationEntity -> {
            return attrAttrgroupRelationEntity.getAttrId();
        }).collect(Collectors.toList());
        if (attrids == null || attrids.size() == 0) {
            return null;
        }
        List<AttrEntity> attrEntities = this.getBaseMapper().selectBatchIds(attrids);
        return attrEntities;
    }

    /**
     * 查询属性分组未关联的属性
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrgroupId) {
        //得到本分类下的未关联的属性 还只能是自己组的未关联属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //先拿到本分类下其他分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groups = attrGroupEntities.stream().map(attrGroupEntity1 -> {
            return attrGroupEntity1.getAttrGroupId();
        }).collect(Collectors.toList());
        //根据其他分组id查询所有关联关系
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groups));
        List<Long> attrIds = attrAttrgroupRelationEntities.stream().map(attrAttrgroupRelationEntity -> {
            return attrAttrgroupRelationEntity.getAttrId();
        }).collect(Collectors.toList());
        //所有本分类下的本组的属性得到
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", 1);
        if (attrIds != null && attrIds.size() > 0) {
            queryWrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        //分页
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    /**
     * 根据attrid获取可以被检索的属性
     *
     * @param longs
     * @return
     */
    @Override
    public List<Long> selectSearchAttrs(List<Long> longs) {
        List<Long> attrEntities = baseMapper.selectSearchAttrs(longs);
        return attrEntities;
    }

}